package smetana.modules.ui.form.io;

import com.google.inject.Inject;

import java.io.File;
import java.io.IOException;

import org.apache.pivot.collections.List;
import org.apache.pivot.wtk.*;
import org.apache.pivot.wtkx.WTKX;
import smetana.domain.join.PriceListImportPosition;
import smetana.modules.io.ExcelImportService;
import smetana.modules.ui.form.AbstractPanel;
import smetana.util.Pivot;
import smetana.util.Work;

/**
 * @author dmitry.mamonov
 */
public class ImportPriceListPanel extends AbstractPanel {
    @Inject
    ExcelImportService excelImportService;

    @WTKX
    TableView tableView;

    @WTKX
    PushButton buttonSelectFile;

    @WTKX
    ActivityIndicator activityIndicator;        

    Action actionSelectFile = new Action() {
        @Override
        public void perform() {
            activityIndicator.setActive(true);
            Pivot.runWork(new Work() {
                List<PriceListImportPosition> positionsList;

                @Override
                public void doWork() {
                    try {
                        positionsList = excelImportService.prepareImportPriceList(new File("import\\price_2009-06-16.xls"));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void publishResults() {
                    tableView.setTableData(positionsList);
                    activityIndicator.setActive(false);
                }

                @Override
                public void failed(Throwable th) {
                    th.printStackTrace(); //TODO подробное логирование.
                    Prompt.prompt("Не удалось загрузить документ", getComponent().getWindow());
                    activityIndicator.setActive(false);
                }
            });
        }
    };

    public ImportPriceListPanel() {
        super();
    }

    @Override
    public void init() {
        buttonSelectFile.setAction(actionSelectFile);
    }
}
